import 'dart:async';
import 'package:example/utils/common.dart';


class Countdown {
  Timer? _timer;
  int count = 0;
  Duration duration;

  Countdown({this.duration = const Duration(seconds: 1)});

  /// 倒计时
  isCountDown() => _timer != null && _timer?.isActive == true;

  startCountDown({Function? updateFun}) {
    if (_timer == null) {
      logger.i("开始倒计时");

      _innerCountDown(updateFun);
      _timer = Timer.periodic(duration, (timer) {
        count = count + 1;
        _innerCountDown(updateFun);
      });
    }
  }

  _innerCountDown(Function? updateFun) {
    updateFun?.call();
  }

  stopCountDown() {
    if (_timer?.isActive == true) {
      logger.i("倒计时结束");
      _timer?.cancel();
      _timer = null;
      count = 0;
    }
  }
}
